package com.pignest.hotel.ajax;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;

import com.pignest.framework.ajax.AjaxResult;
import com.pignest.framework.util.Utils;
import com.pignest.hotel.beans.Duty;
import com.pignest.hotel.beans.DutyLog;
import com.pignest.hotel.beans.User;
import com.pignest.hotel.service.UserService;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.system.Hotel;
import com.pignest.hotel.system.L;
import com.pignest.hotel.system.Permission;
import com.pignest.hotel.util.DateUtil;

/**
 * 值班相关的远程操作
 * */
@RemoteProxy
public class DutyAjax extends HotelAjax {

	/**
	 * 开始一个新的值班
	 * */
	@RemoteMethod
	public String startDuty() {
		User user = getCurrentUser(Permission.RECEPTION);
		if (user == null)
			return "你未被授权";
		UserService service = Services.getUserService();
		Duty duty = service.getDuty(user);
		if (duty != null)
			return "你已经在值班了, 请不要重复";
		duty = new Duty(user, null, 0);
		service.insert(duty);
		L.insert(duty, "开始新值班");
		return null;
	}
	
	/**
	 * 暂停值班
	 * */
	@RemoteMethod
	public String pauseDuty() {
		User user = getCurrentUser(Permission.RECEPTION);
		if (user == null)
			return "你未被授权";
		UserService service = Services.getUserService();
		Duty duty = service.getDuty(user);
		if (duty == null)
			return "你不在值班状态";
		if (duty.getStatus() == Duty.STATUS_ON_DUTY) {
			duty.setEndTime(new Date());
			duty.setStatus(Duty.STATUS_PAUSE);
		} else if (duty.getStatus() == Duty.STATUS_PAUSE) {
			return null;
		} else {
			return "你不在值班状态";
		}
		service.update(duty);
		L.update(duty, "暂停值班");
		return null;
	}
	
	/**
	 * 恢复值班
	 * */
	@RemoteMethod
	public String resumeDuty() {
		User user = getCurrentUser(Permission.RECEPTION);
		if (user == null)
			return "你未被授权";
		UserService service = Services.getUserService();
		Duty duty = service.getDuty(user);
		if (duty == null || duty.getStatus() != Duty.STATUS_PAUSE)
			return "你没有暂停的值班";
		duty.setStatus(Duty.STATUS_ON_DUTY);
		duty.setEndTime(null);
		service.update(duty);
		L.update(duty, "恢复值班");
		return null;
	}
	
	/**
	 * 接受别人的值班
	 * */
	@RemoteMethod
	//userId, cardNumber, workNumber, password, allMoney, handover, reconfirm
	public AjaxResult acceptDuty(String userId, String cardNumber, String workNumber, String password, boolean reconfirm) {
		final User user = getCurrentUser(Permission.RECEPTION);
		if (user == null)
			return AjaxResult.fail("你未被授权");
		final UserService service = Services.getUserService();
		final User previousUser = StringUtils.isNotEmpty(userId) ? service.get(User.class, userId) : service.getUserByWorkNo(workNumber);
		if (previousUser == null)
			return AjaxResult.fail("请输入工号或者刷卡.");
		if (user.getId().equals(previousUser.getId()))
			return AjaxResult.fail("不能转给自己");
		if (StringUtils.isEmpty(userId) && Hotel.checkPassword(previousUser, password))
			return AjaxResult.fail("工号或者密码输入错误.");
		final Duty previousDuty = service.getDuty(previousUser);
		if (previousDuty == null)
			return AjaxResult.fail("选择员工未值班, 无法交接.");
		if (reconfirm) {
			StringBuilder sb = new StringBuilder();
			sb.append("从 ").append(previousUser.getFormalName());
			sb.append(" 在").append(DateUtil.toString(previousDuty.getStartTime(), DateUtil.DEFAULT_DATETIME_FORMAT));
			sb.append("到");
			if (previousDuty.getStatus() == Duty.STATUS_ON_DUTY)
				sb.append("现在的");
			else
				sb.append(DateUtil.toString(previousDuty.getEndTime(), DateUtil.DEFAULT_DATETIME_FORMAT)).append("的");
			sb.append("全部剩余资金(").append(Utils.toPrice(previousDuty.getEndCash())).append(")");
			sb.append("转交给").append(user.getFormalName()).append("\n\n");
			sb.append("交接后, 将结束").append(previousUser.getFormalName()).append("的值班, ");
			sb.append(user.getFormalName()).append("开始值班").append("\n\n");
			sb.append("请确认!");
			return AjaxResult.confirm(sb.toString());
		}
		service.executeInTransaction(new Runnable() {
			@Override
			public void run() {
				previousDuty.finish();
				service.update(previousDuty);
				Duty duty = service.getDuty(user);
				if (duty == null) {
					duty = new Duty(user, previousUser, previousDuty.getEndCash());
					duty.setPreviousUser(previousUser);
					service.insert(duty);
				} else {
					duty.pass(previousDuty.getEndCash());
					service.update(duty);
				}
				DutyLog log = new DutyLog(duty, previousDuty, true);
				service.insert(log);
				L.insert(duty, "接班");
			}
		});
		return AjaxResult.success();
	}
	
	/**
	 * 把当前值班交接给一下
	 * */
	@RemoteMethod
	public AjaxResult passDuty(String userId, String cardNumber, String workNumber, String password, boolean reconfirm) {
		final User user = getCurrentUser(Permission.RECEPTION);
		if (user == null)
			return AjaxResult.fail("你未被授权");
		final UserService service = Services.getUserService();
		final User nextUser = StringUtils.isNotEmpty(userId) ? service.get(User.class, userId) : service.getUserByWorkNo(workNumber);
		if (nextUser == null)
			return AjaxResult.fail("请输入工号或者刷卡.");
		if (user.getId().equals(nextUser.getId()))
			return AjaxResult.fail("不能转给自己");
		if (StringUtils.isEmpty(userId) && !Hotel.checkPassword(nextUser, password))
			return AjaxResult.fail("工号或者密码输入错误.");
		final Duty duty = service.getDuty(user);
		if (duty == null)
			return AjaxResult.fail("当前没有值班, 无法交接.");
		if (reconfirm) {
			StringBuilder sb = new StringBuilder();
			sb.append("从 ").append(user.getFormalName());
			sb.append(" 在").append(DateUtil.toString(duty.getStartTime(), DateUtil.DEFAULT_DATETIME_FORMAT));
			sb.append("到");
			if (duty.getStatus() == Duty.STATUS_ON_DUTY)
				sb.append("目前");
			else
				sb.append(DateUtil.toString(duty.getEndTime(), DateUtil.DEFAULT_DATETIME_FORMAT));
			sb.append("的全部剩余资金(").append(Utils.toPrice(duty.getEndCash())).append(")");
			sb.append("转交给").append(nextUser.getFormalName()).append("\n\n");
			sb.append("交接后, 将结束").append(user.getFormalName()).append("的值班, ");
			sb.append(nextUser.getFormalName()).append("开始值班").append("\n\n");
			sb.append("请确认!");
			return AjaxResult.confirm(sb.toString());
		}
		service.executeInTransaction(new Runnable() {
			@Override
			public void run() {
				duty.finish();
				service.update(duty);
				Duty nextDuty = service.getDuty(nextUser);
				if (nextDuty == null) {
					nextDuty = new Duty(nextUser, user, duty.getEndCash());
					nextDuty.setPreviousUser(user);
					service.insert(nextDuty);
				} else {
					nextDuty.pass(duty.getEndCash());
					service.update(nextDuty);
				}
				DutyLog log = new DutyLog(duty, nextDuty, false);
				service.insert(log);
				L.update(duty, "传班");
			}
		});
		return AjaxResult.success();
	}
	
	@RemoteMethod
	public String reserve(String amount) {
		if (!Utils.checkPrice(amount))
			return "输入的金额不合法";
		final int money = Utils.toPrice(amount);
		if (money <= 0)
			return ("输入的金额不合法");
		final Duty duty = Hotel.getCurrentDuty();
		if (duty == null)
			return ("当前没有值班, 无法交接.");
		final UserService service = Services.getUserService();
		service.executeInTransaction(new Runnable() {
			@Override
			public void run() {
				duty.reserve(money);
				service.update(duty);
				DutyLog log = new DutyLog(duty, money);
				service.insert(log);
			}
		});
		return null;
	}
	
	@RemoteMethod
	public AjaxResult withdraw(String userId, String cardNumber, String workNumber, String password, boolean reconfirm, String amount) {
		if (!Utils.checkPrice(amount))
			return AjaxResult.fail("输入的金额不合法");
		final int money = Utils.toPrice(amount);
		if (money <= 0)
			return AjaxResult.fail("输入的金额不合法");
		final User user = getCurrentUser(Permission.RECEPTION);
		if (user == null)
			return AjaxResult.fail("你未被授权");
		final UserService service = Services.getUserService();
		final User nextUser = StringUtils.isNotEmpty(userId) ? service.get(User.class, userId) : service.getUserByWorkNo(workNumber);
		if (nextUser == null)
			return AjaxResult.fail("请输入工号或者刷卡.");
		if (!Permission.ACCOUNT_MANAGER.alow(nextUser))
			return AjaxResult.fail(nextUser.getFormalName() + "没有财务权限.");
		if (user.getId().equals(nextUser.getId()))
			return AjaxResult.fail("不能自己提取");
		if (!Hotel.checkPassword(nextUser, password))
			return AjaxResult.fail("工号或者密码输入错误.");
		final Duty duty = service.getDuty(user);
		if (duty == null)
			return AjaxResult.fail("当前没有值班, 无法交接.");
		if (money > 0 && money > duty.getEndCash())
			return AjaxResult.fail("提取的金额超过当前值班的剩余资金");
		if (reconfirm) {
			StringBuilder sb = new StringBuilder();
			sb.append("从 ").append(user.getFormalName());
			sb.append("值班的资金中提取 ").append(Utils.toPrice(money)).append(",");
			sb.append(" 给财务 ").append(nextUser.getFormalName()).append("\n\n");
			sb.append("请确认!");
			return AjaxResult.confirm(sb.toString());
		}
		service.executeInTransaction(new Runnable() {
			@Override
			public void run() {
				duty.withdraw(money);
				service.update(duty);
				L.update(duty, "财务提款");
			}
		});
		return AjaxResult.success();
	}
}
